<?php
// +----------------------------------------------------------------------
// | Class  Helper 系统基础方法
// +----------------------------------------------------------------------
// | Copyright (c) 2020
// +----------------------------------------------------------------------

/**
 * 设置sessions
 */
if(!function_exists('sys_sessions_set')){
    function sys_sessions_set($name, $val){
        if(SYS_PHP_VERSION >= '5.4'){
            if(!session_status() != 2){
                session_start();
            }
        }else{
            if(!session_id()){
                session_start();
            }
        }
        $_SESSION[$name] = $val;
        session_commit(); //别名session_write_close();
    }
}

/**
 * 获取sessions
 */
if(!function_exists('sys_sessions_get')){
    function sys_sessions_get($name){
        if(SYS_PHP_VERSION >= '5.4'){
            if(session_status() != 2){
                session_start();
            }
        }else{
            if(!session_id()){
                session_start();
            }
        }
        $info = isset($_SESSION[$name]) ? $_SESSION[$name] : null;
        session_commit();
        return $info;
    }
}

/**
 * 删除sessions
 */
if(!function_exists('sys_sessions_del')){
    function sys_sessions_del($name){
        if(!isset($_SESSION[$name])){
            return false;
        }
        unset($_SESSION[$name]);
        session_commit();
    }
}

/**
 * 清空所有session
 */
if(!function_exists('sys_sessions_clear')){
    function sys_sessions_clear($name=''){
        if(SYS_PHP_VERSION >= '5.4'){
            if(!session_status() != 2){
                session_start();
            }
        }else{
            if(!session_id()){
                session_start();
            }
        }
        $_SESSION = array(); // 删除所有 Session 变量
        //判断 cookie 中是否保存 Session ID 存在清理cookie
        if(isset($_COOKIE[session_name()])){
            setcookie(session_name(),'',time()-3600, '/');
        }
        session_destroy(); //删除当前用户对应的session文件以及释放session id，内存中的$_SESSION变量内容依然保留
        return true;
    }
}

/**
 * 设置cookie
 */
if(!function_exists('sys_cookies_set')){
    function sys_cookies_set($name, $val, $expire = 604800){ // 默认7天
        $expire += time();
        //ob_start();
        setcookie($name, $val, $expire, '/');
        //ob_end_flush();
        $_COOKIE[$name] = $val;
    }
}

/**
 * 获取cookie
 */
if(!function_exists('sys_cookies_get')){
	function sys_cookies_get($name){
		if(isset($_COOKIE[$name])){
			return $_COOKIE[$name];
		}
		return null;
	}
}

/**
 * 删除cookie
 */
if(!function_exists('sys_cookies_del')){
	function sys_cookies_del($name){
		setcookie($name, 'null', time() - 1000, '/');
	}
}

/**
 * 运行开销统计
 */
if(!function_exists('sys_costs')){
	function sys_costs(){
		return array(
			'times'=>round((microtime(true) - SYS_INIT_TIME), 3),
			'ram'=>round((memory_get_usage() - SYS_INIT_MEMORY) / 1024, 2)
		);
	}
}

/**
 * 重定向
 */
if(!function_exists('sys_redirect')){
    function sys_redirect($url){
        if($url){
            if(stripos($url,'http://') == false && stripos($url,'https://') == false){
                $url = SYS_HOST.$url.SYS_URL_FIX;
            }
        }else{
            $url = SYS_HOST;
        }
        header("Location: ".$url);exit;
    }
}

/**
 * js提示跳转
 */
if(!function_exists('sys_jump')){
	function sys_jump($txt = '提示', $url = ''){
		$txt = strval($txt);
		if($url){
            $httpType = '';
            if(strpos($url,'http://') !== false){
                $httpType = 'http://';
            }else if(strpos($url,'https://') !== false){
                $httpType = 'https://';
            }
            $url = $httpType ? $url : SYS_HOST.$url;
            echo "<script>alert('".$txt."');window.location.href='".$url."';</script>";
        }else{
            echo "<script>alert('".$txt."');window.history.go(-1);</script>";
        }
	}
}

/**
 * 路由拼接
 */
if(!function_exists('sys_url_path')){
    function sys_url_path($url){
        return SYS_HOST.$url.SYS_URL_FIX;
    }
}

/**
 * 模版内加载模版路径辅助
 */
if(!function_exists('sys_tmpl')){
    function sys_tmpl($tmpl){
        return SYS_VIEW_PATH.$tmpl.SYS_TMPL_FIX;
    }
}

/**
 * debug信息获取
 */
if(!function_exists('sys_debug_get')){
    function sys_debug_info($vals = array()){
        $err = array();
        foreach($vals as $v){
            $file = isset($v['file']) ? 'ErrFile in '.$v['file'] : '';
            $line = isset($v['line']) ? ' on line '.$v['line'] : '';
            $class = isset($v['class']) ? ' & Class is '.$v['class'] : '';
            $function = isset($v['function']) ? ' and Function is '.$v['function'] : '';
            $err[] = $file.$line.$class.$function;
        }
        return $err;
    }
}

/**
 * 系统日志
 */
if(!function_exists('sys_err_loger')){
    function sys_err_loger($str, $file='', $line=0){
        $debug = sys_debug_info(debug_backtrace());
        $file = $file ? ' in '.$file : '';
        $line = $line ? ' on line '.$line : '';
        $str = $str.$file.$line;
        if($str){
            array_unshift($debug, $str);
        }
        if(SYS_DEBUG_LOG){
            sys_err_print($debug);
        }
        if(SYS_PAGE404){
            header("Location: ".SYS_HOST."404.html");
        }else if(SYS_DEBUG){
            sys_logerr($debug);
        }
        exit;
    }
}

/**
 * 系统日志
 */
if(!function_exists('sys_err_print')){
    function sys_err_print($str){
        is_array($str) && $str = print_r($str,true);
        is_object($str) && $str = print_r($str,true);
        $errorStr = '[' . date('Y-m-d H:i:s') . '][LOG] '.$str . PHP_EOL;
        error_log($errorStr, 3, SYS_PATH.SYS_DEBUG_LOG_PATH . 'SYS' .date('Y_m_d') . '.log', 'extra');
    }
}

/**
 * sql日志db
 */
if(!function_exists('sys_db_loger')){
    function sys_db_loger($str){
        if(!SYS_DB_LOG){
            return '';
        }
        // 日志目录创建
        if(!file_exists(SYS_DB_LOG_PATH)){
            sys_add_path(SYS_DB_LOG_PATH);
        }
        is_array($str) && $str = print_r($str,true); //print_r 增加 true 返回打印字符窜
        is_object($str) && $str = print_r($str,true);
        $errorStr = '[' . date('Y-m-d H:i:s') . '][LOG] '.$str . PHP_EOL;
        error_log($errorStr, 3, SYS_PATH.SYS_DB_LOG_PATH . 'DB' .date('Y_m_d') . '.log', 'extra');
    }
}

/**
 * 程序日志 print_r
 */
if(!function_exists('sys_logerr')) {
    function sys_logerr($s){
        echo '<pre>';
        print_r($s);
        echo '</pre>';
        exit;
    }
}

/**
 * 程序日志 var_dump
 */
if(!function_exists('sys_logerd')) {
    function sys_logerd($s){
        echo '<pre>';
        var_dump($s);
        echo '</pre>';
        exit;
    }
}

/**
 * 程序日志
 */
if(!function_exists('sys_loger')){
    function sys_loger($str){
        if(!SYS_RUN_LOG){
            return '';
        }
        // 日志目录创建
        if(!file_exists(SYS_RUN_LOG_PATH)){
            sys_add_path(SYS_RUN_LOG_PATH);
        }
        is_array($str) && $str = print_r($str,true); //print_r 增加 true 返回打印字符窜
        is_object($str) && $str = print_r($str,true);
        $errorStr = '[' . date('Y-m-d H:i:s') . '][LOG] '.$str . PHP_EOL;
        error_log($errorStr, 3, SYS_PATH.SYS_RUN_LOG_PATH . 'LOG' .date('Y_m_d') . '.log', 'extra');
    }
}

/**
 * Notes: 字符串-加密
 * Desc: 兼容字符串特殊字符加密
 */
if(!function_exists('sys_encrypt')) {
    function sys_encrypt($string, $key)
    {
        $string = base64_encode(openssl_encrypt($string, 'AES-128-ECB', $key, OPENSSL_RAW_DATA));
        return rtrim(strtr($string, '+/', '-_'), '=');
    }
}

/**
 * Notes: 字符串-解密
 * Desc: 兼容字符串特殊字符解密
 */
if(!function_exists('sys_decrypt')) {
    function sys_decrypt($string, $key)
    {
        $string = str_pad(strtr($string, '-_', '+/'), strlen($string) % 4, '=', STR_PAD_RIGHT);
        return openssl_decrypt(base64_decode($string), 'AES-128-ECB', $key, OPENSSL_RAW_DATA);
    }
}

/**
 * Notes: 客户端操作限制
 * User: ZHL
 * Date: 2020/5/5
 */
if(!function_exists('sys_cookies_count')) {
    function sys_cookies_count($kname, $kcount){
        $limitFlag = sys_cookies_get($kname);
        if (!$limitFlag) {
            $counts = base64_encode(base64_encode(1));
            sys_cookies_set($kname, $counts,86400);
        } else {
            $counts = intval(base64_decode(base64_decode($limitFlag)));
            if ($counts >= $kcount) {
                return false;
            }
            $counts = base64_encode(base64_encode($counts + 1));
            sys_cookies_set($kname, $counts,86400);
        }
        return true;
    }
}

/**
 * Notes: 循环创建目录
 * User: ZhuHaili
 */
if (!function_exists('sys_add_path')) {
    function sys_add_path($path){
        if (!file_exists($path)){
            sys_add_path(dirname($path));
            mkdir($path, 0777);
        }
    }
}